import axios from "axios";
import { loginOut } from "@/store/modules/user";
import { showModal } from "@/store/modules/user";
import { message } from "antd";
import store from "@/store";

const serviceSteam = axios.create({
  timeout: 5000,
  baseURL: "http://127.0.0.1:6789/api",
  timeoutErrorMessage: "请求超时，请稍后再试",
});

serviceSteam.interceptors.request.use(
  (config) => {
    if (config.data) {
      config.data.accessToken = localStorage.getItem("accessToken");
      config.data.refreshToken = localStorage.getItem("refreshToken");
    }
    config.headers.Authorization = localStorage.getItem("accessToken");
    return config;
  },
  (error) => {
    console.log("3333", error);
    return Promise.reject(error);
  }
);

serviceSteam.interceptors.response.use(
  (response) => {
    if (response.data.status === 401) {
      message.error("登录已过期，请重新登录");
      console.log("555", loginOut());
      store.dispatch(loginOut());
      store.dispatch(showModal());
    }
    return response;
  },
  (error) => {
    console.log("请求出错：", error);
    if (error.code === "ERR_NETWORK") {
      message.error("请求超时，请检查网络连接");
      // 这里可以添加你的超时提示逻辑，比如弹窗等
    }
  }
);

//失败提示
/* function msag(err) {
  if (err && err.response) {
    switch (err.response.status) {
      case 400:
        alert(err.response.data.error.details);
        break;
      case 401:
        alert("未授权，请登录");
        break;

      case 403:
        alert("拒绝访问");
        break;

      case 404:
        alert("请求地址出错");
        break;

      case 408:
        alert("请求超时");
        break;

      case 500:
        alert("服务器内部错误");
        break;

      case 501:
        alert("服务未实现");
        break;

      case 502:
        alert("网关错误");
        break;

      case 503:
        alert("服务不可用");
        break;

      case 504:
        alert("网关超时");
        break;

      case 505:
        alert("HTTP版本不受支持");
        break;
      default:
    }
  }
} */

export default serviceSteam;
